<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="!form.id ? $t('add') : $t('update')"
    :visible.sync="visible"
    width="80vw"
  >
    <el-form
      :model="form"
      :rules="dataRule"
      label-width="120px"
      ref="dataForm"
      v-loading="loading"
    >
      <el-form-item
        label="菜谱名称"
        prop="title">
        <el-input
          placeholder="菜谱名称"
          v-model="form.title"/>
      </el-form-item>

      <!--      <el-form-item label="描述" prop="descri">-->
      <!--        <el-input-->
      <!--          type="textarea"-->
      <!--          :autosize="{ minRows: 5, maxRows: 8 }"-->
      <!--          placeholder="描述"-->
      <!--          v-model="form.descri"-->
      <!--        ></el-input>-->
      <!--      </el-form-item>-->

      <!--      <el-form-item label="第一段配图" prop="story1Url">-->
      <!--        <el-upload-->
      <!--          :file-list="story1FileList"-->
      <!--          :limit="1"-->
      <!--          :multiple="false"-->
      <!--          :on-exceed="handleStory1ImgFileExceed"-->
      <!--          :on-preview="onStory1ImgPreview"-->
      <!--          :on-remove="onStory1ImgRemoved"-->
      <!--          :on-success="onStory1ImgUploadSuccess"-->
      <!--          accept="image/png, image/jpeg"-->
      <!--          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"-->
      <!--          list-type="picture-card"-->
      <!--        >-->
      <!--          <i class="el-icon-plus"></i>-->
      <!--        </el-upload>-->
      <!--      </el-form-item>-->

      <!--      <el-form-item label="第二段文字" prop="story2Text">-->
      <!--        <el-input placeholder="第二段文字" v-model="form.story2Text"></el-input>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="第二段配图" prop="story2Url">-->
      <!--        <el-upload-->
      <!--          :file-list="story2FileList"-->
      <!--          :limit="1"-->
      <!--          :multiple="false"-->
      <!--          :on-exceed="handleStory2ImgFileExceed"-->
      <!--          :on-preview="onStory2ImgPreview"-->
      <!--          :on-remove="onStory2ImgRemoved"-->
      <!--          :on-success="onStory2ImgUploadSuccess"-->
      <!--          accept="image/png, image/jpeg"-->
      <!--          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"-->
      <!--          list-type="picture-card"-->
      <!--        >-->
      <!--          <i class="el-icon-plus"></i>-->
      <!--        </el-upload>-->
      <!--      </el-form-item>-->

      <el-form-item
        label="菜谱"
        prop="menuId">
        <el-select
          class="recipe-select"
          :remote="getRecipes"
          placeholder="选择菜谱"
          v-model="form.menuId"
        >
          <el-option
            :key="item.id"
            :label="item.name"
            :value="item.id"
            v-for="item in recipes"
          >
            <div class="recipe-select-item">
              <midea-admin-image
                :height="30"
                :previewable="true"
                :url="item.picUrl"
                :width="30"
              />
              <span class="recipe-select-item__name">{{ item.name }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="美食手绘图"
        prop="menuUrl">
        <div class="image-desc">图片尺寸：(一倍图：375*501；二倍图：750*1002)</div>
        <el-upload
          :file-list="menuUrlFileList"
          :limit="1"
          :multiple="false"
          :on-exceed="handleMenuImgFileExceed"
          :on-preview="onMenuImgPreview"
          :on-remove="onMenuImgRemoved"
          :on-success="onMenuImgUploadSuccess"
          accept="image/png, image/jpeg"
          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"
          list-type="picture-card"
        >
          <i class="el-icon-plus"/>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="描述"
        prop="story1Text">
        <el-input
          type="textarea"
          :autosize="{ minRows: 5, maxRows: 8 }"
          placeholder="描述"
          v-model="form.story1Text"
        />
      </el-form-item>

      <el-form-item
        label="推荐产品"
        prop="ext">
        <el-select
          class="product-select"
          :remote="getProducts"
          placeholder="选择产品"
          v-model="form.ext"
        >
          <el-option
            :key="item.recommendProductUrl"
            :label="item.recommendProductText"
            :value="item.recommendProductUrl"
            v-for="item in products"
          >
            <span>{{ item.recommendProductText }}</span>
            <span v-if="item.sn8 && item.sn8.length > 0">({{ item.sn8 }})</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="分享文案"
        prop="shareText">
        <el-input
          placeholder="分享文案"
          v-model="form.shareText"/>
      </el-form-item>
      <el-form-item
        label="分享底图"
        prop="shareUrl">
        <!--        <div class="image-desc">图片尺寸：(375*501)</div>-->
        <div class="image-desc">图片尺寸：(一倍图：308*442；二倍图：616*884)</div>
        <el-upload
          :file-list="shareUrlFileList"
          :limit="1"
          :multiple="false"
          :on-exceed="handleShareImgFileExceed"
          :on-preview="onShareImgPreview"
          :on-remove="onShareImgRemoved"
          :on-success="onShareImgUploadSuccess"
          accept="image/png, image/jpeg"
          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"
          list-type="picture-card"
        >
          <i class="el-icon-plus"/>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-dialog
      :append-to-body="true"
      :visible.sync="previewDialogVisible">
      <img
        :src="previewImgUrl"
        alt=""
        width="100%" >
    </el-dialog>

    <template slot="footer">
      <el-button
        :loading="requesting"
        @click="visible = false">{{
          $t("cancel")
        }}</el-button>
      <el-button
        :loading="requesting"
        @click="dataFormSubmitHandle()"
        type="primary"
      >{{ $t("confirm") }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import mixinViewModule from '@/mixins/mike.view-module'
export default {
  name: 'FoodstoryAddOrUpdate',
  mixins: [mixinViewModule],
  data () {
    return {
      visible: false,
      loading: false,
      requesting: false,
      cities: [],
      recipes: [],
      products: [],
      mixinViewModuleOptions: {
        // isGourmetMap: true,
        // getDataListURL: '/midea/menu/foodmap/foodstorys/allmenus',
        // getDataListIsPage: true,
        // deleteURL: '/midea/menu/foodmap/foodstorys/del/',
        // deleteIsBatch: true
      },
      story1FileList: [],
      story2FileList: [],
      menuUrlFileList: [],
      shareUrlFileList: [],
      previewImgUrl: '',
      previewDialogVisible: false,
      form: {
        menuId: '', // 绑定的菜谱Id
        menuUrl: '', // 绑定的菜谱图片
        createTime: '',
        descri: '',
        ext: '',
        flag: 0,
        id: '',
        story1Text: '', // 第一段文字
        story1Url: '', // 第一张图URl
        story2Text: '', // 第二段文字
        story2Url: '', // 第二张图URl
        title: '', // 标题
        totalCounts: 0,
        shareText: '', // 分享文案
        shareUrl: '' // 分享底图
      }
    }
  },
  computed: {
    dataRule () {
      return {
        title: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        menuId: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        menuUrl: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]

        // cityId: [
        //   {
        //     required: true,
        //     message: this.$t('validate.required'),
        //     trigger: 'blur'
        //   }
        // ]
        // productTypeId: [
        //     {
        //         required: true,
        //         message: this.$t('validate.required'),
        //         trigger: 'blur'
        //     }
        // ]
      }
    }
  },
  mounted () {
    this.getCities()
  },
  methods: {
    reset () {
      this.$refs['dataForm'] && this.$refs['dataForm'].resetFields()
      this.story1FileList = []
      this.story2FileList = []
      this.menuUrlFileList = []
      this.shareUrlFileList = []

      this.recipes = []
      this.form = {
        menuId: '', // 绑定的菜谱Id
        menuUrl: '', // 绑定的菜谱图片
        createTime: '',
        descri: '',
        ext: '',
        flag: 0,
        id: '',
        story1Text: '', // 第一段文字
        story1Url: '', // 第一张图URl
        story2Text: '', // 第二段文字
        story2Url: '', // 第二张图URl
        title: '', // 标题
        totalCounts: 0,
        shareText: '', // 分享文案
        shareUrl: '' // 分享底图
      }
    },
    init () {
      this.visible = true

      this.$nextTick(() => {
        if (this.form.id && this.form.id.length > 0) {
          if (this.form.story1Url && this.form.story1Url.length > 0) {
            this.story1FileList = [
              { name: this.form.story1Url, url: this.form.story1Url }
            ]
          }

          if (this.form.story2Url && this.form.story2Url.length > 0) {
            this.story2FileList = [
              { name: this.form.story2Url, url: this.form.story2Url }
            ]
          }

          if (this.form.menuUrl && this.form.menuUrl.length > 0) {
            this.menuUrlFileList = [
              { name: this.form.menuUrl, url: this.form.menuUrl }
            ]
          }
          if (this.form.shareUrl && this.form.shareUrl.length > 0) {
            this.shareUrlFileList = [
              { name: this.form.shareUrl, url: this.form.shareUrl }
            ]
          }
        }

        this.getRecipes()
        this.getProducts()
        // Promise.race([ ])
      })
    },

    // async getInfo () {
    //   if (this.loading) {
    //     return
    //   }
    //   this.loading = true
    //   this.$http
    //     .post(`${this.mikeNetworkBase}midea/menu/foodmap/citystorys/get`, {
    //       id: this.form.id,
    //       user: {
    //         userId: 'manager_user',
    //         userName: 'manager_user'
    //       }
    //     }).then(({ data: res }) => {
    //       console.log(res)
    //       this.loading = false
    //       // this.form = res.data
    //     }).finally(() => {
    //       this.loading = false
    //     })
    // },

    async getProducts () {
      this.$http
        .post(
          `${this.mikeNetworkBase}midea/menu/foodmap/foodstorys/getallproduct`
        )
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }

          this.products = res.data
        })
    },
    async getRecipes () {
      this.$http
        .post(`${this.mikeNetworkBase}midea/menu/foodmap/foodstorys/allmenus`)
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }

          this.recipes = res.data
        })
    },
    async getCities () {
      this.$http
        .post(`${this.mikeNetworkBase}midea/menu/foodmap/common/citys/`)
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }

          this.cities = res.data
        })
    },
    /** *imgs event */
    handleStory1ImgFileExceed (type) {
      this.$message.warning(`只能设置一张图片哦`)
    },

    onStory1ImgPreview () {
      this.previewImgUrl = this.form.story1Url
      this.previewDialogVisible = true
    },
    onStory1ImgRemoved () {
      this.form.story1Url = ''
    },
    onStory1ImgUploadSuccess (response) {
      if (response.code !== 200) {
        this.form.story1Url = ''
        return
      }
      this.form.story1Url = response.data
    },
    handleMenuImgFileExceed (type) {
      this.$message.warning(`只能设置一张图片哦`)
    },

    onMenuImgPreview () {
      this.previewImgUrl = this.form.menuUrl
      this.previewDialogVisible = true
    },
    onMenuImgRemoved () {
      this.form.menuUrl = ''
    },
    onMenuImgUploadSuccess (response) {
      if (response.code !== 200) {
        this.form.menuUrl = ''
        return
      }
      this.form.menuUrl = response.data
    },

    handleShareImgFileExceed (type) {
      this.$message.warning(`只能设置一张图片哦`)
    },

    onShareImgPreview () {
      this.previewImgUrl = this.form.shareUrl
      this.previewDialogVisible = true
    },
    onShareImgRemoved () {
      this.form.shareUrl = ''
    },
    onShareImgUploadSuccess (response) {
      if (response.code !== 200) {
        this.form.shareUrl = ''
        return
      }
      this.form.shareUrl = response.data
    },
    handleStory2ImgFileExceed (type) {
      this.$message.warning(`只能设置一张图片哦`)
    },

    onStory2ImgPreview () {
      this.previewImgUrl = this.form.story2Url
      this.previewDialogVisible = true
    },
    onStory2ImgRemoved () {
      this.form.story2Url = ''
    },
    onStory2ImgUploadSuccess (response) {
      if (response.code !== 200) {
        this.form.story2Url = ''
        return
      }
      this.form.story2Url = response.data
    },
    dataFormSubmitHandle () {
      this.$refs['dataForm'].validate(valid => {
        if (!valid) {
          return false
        }
        if (this.requesting) {
          return
        }
        let params = {
          ...this.form
          // status: this.form.status ? 1 : 0
        }

        if (params.ext && params.ext.length > 0) {
          let product = this.products.find(item => {
            return item.recommendProductUrl === params.ext
          })

          params.descri = product.recommendProductText
        }

        this.requesting = true
        this.$http
          .post(
            `${this.mikeNetworkBase}midea/menu/foodmap/foodstorys/save`,
            params
          )
          .then(({ data: res }) => {
            if (res.code !== 200) {
              return this.$message.error(res.msg)
            }
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
          .catch(() => {})
          .finally(() => {
            this.requesting = false
          })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.recipe-select-item {
  display: flex;
  flex-direction: row;
  color: #333333;
  font-size: 14px;
}
.recipe-select-item__name {
  margin-left: 5px;
}
.image-desc {
  color: #999999;
  margin-bottom: 10px;
}
</style>
